Binary Search Trees: Core Operations

PolyU DSAI2201 Lecture 13 2025-11-25

Binary Search Trees (BST): The Ordering Invariant

The Binary Search Tree structure is fundamental because it imposes a strict ordering invariant on all nodes, enabling efficient search and insertion.

Left Subtree Value<Root Value<Right Subtree Value \text{Left Subtree Value} < \text{Root Value} < \text{Right Subtree Value}

Searching and Insertion Mechanics

Both searching for a key KK and inserting a new node follow the same pathfinding logic starting from the root:

  1. Comparison: Compare KK to the Current Node's value.
  2. Path Selection: If K<Current NodeK < \text{Current Node}, move Left (L); if K>Current NodeK > \text{Current Node}, move Right (R).
  3. Termination (Search): Stop when the node is found or when a NULL pointer is reached (key not present).
  4. Termination (Insertion): The new node is attached at the final NULL position found.

This directed traversal ensures that, in a balanced tree, the maximum number of comparisons needed is O(logn)O(\log n).

Successor & Predecessor: Key to Deletion

Finding the in-order Successor (the node with the next largest key) is essential for the deletion algorithm when the node to be removed has two children.

  1. If node NN has a Right Child: The successor is the minimum value in the right subtree. Move one step Right, then continuously follow Left pointers.
  2. If node NN has NO Right Child: The successor is the nearest ancestor AA for which NN is in AA's left subtree.

Performance Characteristics: O(logn)O(\log n) vs. O(n)O(n)

BSTs provide logarithmic performance only if the tree remains relatively balanced. If data is inserted in sorted order, the tree degenerates into a skewed list, resulting in worst-case linear time complexity.

OperationAverage Case (Balanced)Worst Case (Skewed)
SearchO(logn)O(\log n)O(n)O(n)
InsertionO(logn)O(\log n)O(n)O(n)
DeletionO(logn)O(\log n)O(n)O(n)
Finding SuccessorO(logn)O(\log n)O(n)O(n)
📝 Interactive Quiz

1. What is the sequence of moves (R/L) to search for 80?

Assume a BST is built with keys: 50, 25, 75, 60, 90, 80. The root is 50.

  • A) R → R → L
  • B) R → L → R
  • C) L → R → R
  • D) R → R → R

2. What scenario leads to the worst-case O(n)O(n) search time in a BST?

  • A) The tree is perfectly balanced.
  • B) Inserting elements in sorted order.
  • C) The tree contains duplicate values.
  • D) Searching for the minimum element.

3. In the same BST (root 50), what is the in-order successor of the node with value 75?

The tree contains: 50, 25, 75, 60, 90, 80.

  • A) 90
  • B) 60
  • C) 80
  • D) 50

4. According to the BST ordering invariant, if a node has value 42, which value could NOT be in its left subtree?

  • A) 10
  • B) 55
  • C) 41
  • D) -5